package com.zdxf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.regexp.internal.RE;
import com.zdxf.compoent.WebSocketServer;
import com.zdxf.conf.Constant;
import com.zdxf.domain.LogDO;
import com.zdxf.domain.ServiceDO;
import com.zdxf.domain.SiteXmlDO;
import com.zdxf.domain.SystemInfoDO;
import com.zdxf.mapper.ServiceManageMapper;
import com.zdxf.param.LogParam;
import com.zdxf.service.ServiceManageService;
import com.zdxf.util.Result;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ServiceManageServiceImpl implements ServiceManageService {
    @Autowired
    ServiceManageMapper serviceManageMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<ServiceDO> getServiceListNoStatus() {
        double num = 5.4;
char ame = '3';
        List<ServiceDO> serviceList = serviceManageMapper.getServiceList();
        return serviceList;
    }

    @Override
    public List<ServiceDO> getServiceList() throws IOException {
        List<ServiceDO> serviceList = serviceManageMapper.getServiceList();
        for (int i = 0; i < serviceList.size(); i++) {
            //通过http来判断服务是否启动
            if (serviceList.get(i).getTestUrl() != null) {
                try {
                    ResponseEntity<String> exchange = restTemplate.exchange(serviceList.get(i).getTestUrl(), HttpMethod.GET, null, String.class);
                    serviceList.get(i).setStatus(1);
                } catch (Exception e) {
                    serviceList.get(i).setStatus(0);
                }
            } else if (serviceList.get(i).getTestSh() != null) {
                //通过sh来判断服务是否启动
                Process process = null;
                if (serviceList.get(i).getIp() != null) {
                    process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ssh " + serviceList.get(i).getUser() + "@" + serviceList.get(i).getIp() + " " + serviceList.get(i).getTestSh()});
                } else {
                    process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", serviceList.get(i).getTestSh()});
                }
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));
                String s;
                while ((s = reader.readLine()) != null) {
                    System.out.println("===--------asdasdas");
                    System.out.println(s);
                    System.out.println("===--------asdasdas");
                    //zkService
                    if (serviceList.get(i).getName().equals("zkService") && s.indexOf("Mode") != -1) {
                        //if (serviceList.get(i).getName().equals("zkService") ) {
                        System.out.println("===--------asdasda22222s");
                        System.out.println(s);
                        System.out.println("===--------asdasda2222s");
                        serviceList.get(i).setStatus(1);
                    }
                    //hive
                    if (serviceList.get(i).getName().equals("hive")) {
                        serviceList.get(i).setStatus(1);
                    }
                    //spark
                    if (serviceList.get(i).getName().equals("spark")) {
                        serviceList.get(i).setStatus(1);
                    }
                }
            }
        }
        return serviceList;
    }

    @Override
    public ServiceDO startServiceById(int id) throws IOException {
        ServiceDO res = serviceManageMapper.getServiceById(id);
        Process process = null;
        if (res.getIp() != null) {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ssh " + res.getUser() + "@" + res.getIp() + " " + res.getStartSh()});
        } else {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", res.getStartSh()});
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        String s;
        while ((s = reader.readLine()) != null) {
            WebSocketServer.sendInfo(s);
        }
        res.setStatus(1);
        serviceManageMapper.setServiceEditStatus(res.getId(), 0);
        return res;
    }

    @Override
    public ServiceDO stopServiceById(int id) throws IOException {
        ServiceDO res = serviceManageMapper.getServiceById(id);
//        String[] command = res.getStopSh().split(" ");
//        Process process = Runtime.getRuntime().exec(command);
        Process process = null;
        if (res.getIp() != null) {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ssh " + res.getUser() + "@" + res.getIp() + " " + res.getStopSh()});
        } else {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", res.getStopSh()});
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        String s;
        while ((s = reader.readLine()) != null) {
            WebSocketServer.sendInfo(s);
//            if (s.contains("secondarynamenode")) {
//                res.setStatus(0);
//            }
        }
        res.setStatus(0);
        serviceManageMapper.setServiceEditStatus(res.getId(), 0);
        return res;
    }


    @Override
    public List<SiteXmlDO> getSiteList(int id) throws DocumentException {
        List<SiteXmlDO> fileList = serviceManageMapper.getFileList(id);
        List<SiteXmlDO> siteList = serviceManageMapper.getSiteList(id);

        for (int i = 0; i < fileList.size(); i++) {
            for (int j = 0; j < siteList.size(); j++) {
                Map dataMap = new HashMap<>();
                dataMap.put("path", fileList.get(i).getFilePath());
                HttpEntity httpEntity = new HttpEntity(dataMap);
                String url = "http://" + fileList.get(i).getIp() + ":9203/client/xml/getXmlFile";
                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
                String body = exchange.getBody();
                Document document = DocumentHelper.parseText(body);// getDocument(fileList.get(i).getFilePath());
                HashMap<String, Object> params = new HashMap<>(Constant.HASH_MAP_SIZE);
                if (document != null) {
                    List elementList = document.selectNodes("/configuration/property");
                    for (int k = 0; k < elementList.size(); k++) {
                        Element element = (Element) elementList.get(k);
                        Element nameElement = element.element("name");
                        Element valueElement = element.element("value");
                        if (nameElement.getText().equals(siteList.get(j).getName())) {
                            params.put("id", siteList.get(j).getId());
                            params.put("value", valueElement.getText());
                            serviceManageMapper.setSite(params);
                        }

                    }
                }
            }
        }
        return serviceManageMapper.getSiteList(id);
    }


    @Override
    public Result updateSite(Map params) throws Exception {
        SiteXmlDO res = serviceManageMapper.getSiteById(params);
        List<SiteXmlDO> list = serviceManageMapper.getSiteHostsById(params);
        String data = "修改成功";
        if (!params.get("value").equals(res.getValue())) {
            serviceManageMapper.setSite(params);
            serviceManageMapper.setServiceEditStatus(res.getServiceId(), 1);
            for (int i = 0; i < list.size(); i++) {
                Map dataMap = new HashMap<>();
                dataMap.put("path", list.get(i).getFilePath());
                dataMap.put("name", list.get(i).getName());
                dataMap.put("value",(String) params.get("value"));
                HttpEntity httpEntity = new HttpEntity(dataMap);
                String url = "http://" + list.get(i).getIp() + ":9203/client/xml/putXmlFile";
                restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            }
        } else {
            data = "内容无变化";
        }

        return new Result(true, 20000, "成功", data);
    }

    @Override
    public Result getLogLine(LogParam logParam) {
        Map dataMap = new HashMap<>();
        LogDO logInfo = serviceManageMapper.getLogById(logParam.getId());
        dataMap.put("path", logParam.getPath());
        dataMap.put("numLastLineToRead", logParam.getNumLastLineToRead());
        HttpEntity httpEntity = new HttpEntity(dataMap);
        String url = "http://" + logInfo.getIp() + ":9203/client/log/readLine";
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        return new Result(true, 20000, "成功", body);
    }

    @Override
    public Result getFile(LogParam logParam) {
        Map dataMap = new HashMap<>();
        LogDO logInfo = serviceManageMapper.getLogById(logParam.getId());
        dataMap.put("path", logParam.getPath());
        HttpEntity httpEntity = new HttpEntity(dataMap);
        String url = "http://" + logInfo.getIp() + ":9203/client/log/getFile";
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        return new Result(true, 20000, "成功", body);
    }

    @Override
    public Result getLogList(int id) {
        return new Result(true, 20000, "成功", serviceManageMapper.getLogList(id));

    }


    public static Document updateXML(String filePath, String key, String value) throws Exception {
        Document document = getDocument(filePath);
        boolean flag = false;
        if (document != null) {
            // 修改指定节点
            List elementList = document.selectNodes("/configuration/property");
            for (int i = 0; i < elementList.size(); i++) {
                Element element = (Element) elementList.get(i);
                Element nameElement = element.element("name");
                Element valueElement = element.element("value");
                System.out.println("------------------");
                System.out.println(nameElement.getText());
                System.out.println(valueElement.getText());
                System.out.println("-------------------");
                if (nameElement.getText().equals(key)) {

                    valueElement.setText(value);
                    flag = true;
                }

            }
            if (!flag) {
                Element rootElement = document.getRootElement();
                Element parentElement = rootElement.addElement("property");
                parentElement.addElement("name").setText(key);
                parentElement.addElement("value").setText(value);
            }
        }
        return document;
    }

    public static Document insertXML(String filePath, String key, int id, ServiceManageMapper serviceManageMapper) {
        Document document = getDocument(filePath);
        HashMap<String, Object> params = new HashMap<>(Constant.HASH_MAP_SIZE);
        if (document != null) {
            // 修改指定节点
            List elementList = document.selectNodes("/configuration/property");
            for (int i = 0; i < elementList.size(); i++) {
                Element element = (Element) elementList.get(i);
                Element nameElement = element.element("name");
                Element valueElement = element.element("value");
                if (nameElement.getText().equals(key)) {
                    params.put("id", id);
                    params.put("name", key);
                    params.put("value", valueElement.getText());
                    serviceManageMapper.setSite(params);
                }

            }
        }
        return document;
    }

    public static Document getDocument(String filename) {
        File xmlFile = new File(filename);
        Document document = null;
        if (xmlFile.exists()) {
            try {
                SAXReader saxReader = new SAXReader();
                document = saxReader.read(xmlFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return document;
    }


}
